<template>
  <div style="position: relative">
    <div class="verify-img-out" :style="{ height: parseInt(setSize.imgHeight) + vSpace + 'px' }">
      <div class="verify-img-panel" :style="{ width: setSize.imgWidth, height: setSize.imgHeight }">
        <img v-if="backImgBase" class="verify-img" :src="'data:image/png;base64,' + backImgBase" alt="" />
        <div v-show="showRefresh" class="verify-refresh" @click="refresh"><i class="x-icon icon-074"></i> </div>
        <!--        <transition name="tips">-->
        <!--          <span v-if="tipWords" class="verify-tips" :class="passFlag ? 'suc-bg' : 'err-bg'">{{ tipWords }}</span>-->
        <!--        </transition>-->
      </div>
    </div>
    <!-- 公共部分 -->
    <div class="verify-bar-area" :style="{ width: setSize.imgWidth, 'line-height': barSize.height }">
      <span class="verify-msg" v-text="text"></span>
      <div
        class="verify-left-bar"
        :style="{
          width: leftBarWidth !== undefined ? leftBarWidth : barSize.height,
          height: barSize.height,
          background: leftBarBackgroundColor,
          'border-color': leftBarBorderColor,
          transition: transitionWidth
        }"
      >
        <!--        <span class="verify-msg" v-text="finishText"></span>-->
        <div
          class="verify-move-block"
          :style="{
            width: barSize.height,
            height: barSize.height,
            'background-color': moveBlockBackgroundColor,
            left: moveBlockLeft,
            transition: transitionLeft
          }"
          @touchstart="start"
          @mousedown="start"
        >
          <i :class="['verify-icon x-icon', iconClass]"></i>
          <div
            class="verify-sub-block"
            :style="{
              width: Math.floor((parseInt(setSize.imgWidth) * 47) / 310) + 'px',
              height: setSize.imgHeight,
              top: '-' + (parseInt(setSize.imgHeight) + vSpace + 1) + 'px',
              'background-size': setSize.imgWidth + ' ' + setSize.imgHeight
            }"
          >
            <img
              v-if="blockBackImgBase"
              :src="'data:image/png;base64,' + blockBackImgBase"
              alt=""
              style="width: 100%; height: 100%; display: block"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script type="text/babel" lang="ts">
  import { v4 as uuidv4 } from 'uuid'
  import { aesEncrypt } from '../utils/ase'
  import { resetSize } from '../utils/util'
  import { useStore } from '@/store'
  import { computed, onMounted, reactive, ref, watch, nextTick, toRefs, getCurrentInstance } from 'vue'
  export default {
    name: 'VerifySlide',
    props: {
      vSpace: {
        type: Number,
        default: 5
      },
      explain: {
        type: String,
        default: '向右滑动完成验证'
      },
      imgSize: {
        type: Object,
        default: () => ({
          width: '280px',
          height: '158px'
        })
      },
      blockSize: {
        type: Object,
        default: () => ({
          width: '65px',
          height: '65px'
        })
      },
      barSize: {
        type: Object,
        default: () => ({
          width: '280px',
          height: '44px'
        })
      }
    },
    setup(props, context) {
      const captchaType = 'blockPuzzle'
      const { proxy } = getCurrentInstance()
      const $store = useStore()
      let secretKey = ref(''), //后端返回的ase加密秘钥
        passFlag = ref(''), //是否通过的标识
        backImgBase = ref(''), //验证码背景图片
        blockBackImgBase = ref(''), //验证滑块的背景图片
        backToken = ref(''), //后端返回的唯一token值
        startMoveTime = ref(''), //移动开始的时间
        endMoveTime = ref(''), //移动结束的时间
        tipsBackColor = ref(''), //提示词的背景颜色
        tipWords = ref(''),
        text = ref(''),
        finishText = ref(''),
        setSize = reactive({
          imgHeight: 0,
          imgWidth: 0,
          barHeight: 0,
          barWidth: 0
        }),
        top = ref(0),
        left = ref(0),
        moveBlockLeft = ref(undefined),
        leftBarWidth = ref(undefined),
        // 移动中样式
        moveBlockBackgroundColor = ref('#38f'),
        leftBarBorderColor = ref('#ddd'),
        leftBarBackgroundColor = ref('rgba(51, 136, 255, 0.16)'),
        iconClass = ref('icon-075'),
        status = ref(false), //鼠标状态
        isEnd = ref(false), //是够验证完成
        showRefresh = ref(true),
        transitionLeft = ref(''),
        transitionWidth = ref(''),
        startLeft = ref(0)

      const barArea = computed(() => {
        return proxy.$el.querySelector('.verify-bar-area')
      })
      function init() {
        text.value = props.explain
        getPicture()
        nextTick(() => {
          let { imgHeight, imgWidth, barHeight, barWidth } = resetSize(proxy)
          setSize.imgHeight = imgHeight
          setSize.imgWidth = imgWidth
          setSize.barHeight = barHeight
          setSize.barWidth = barWidth
          proxy.$parent.$emit('ready', proxy)
        })

        window.removeEventListener('touchmove', function (e) {
          move(e)
        })
        window.removeEventListener('mousemove', function (e) {
          move(e)
        })

        //鼠标松开
        window.removeEventListener('touchend', function () {
          end()
        })
        window.removeEventListener('mouseup', function () {
          end()
        })

        window.addEventListener('touchmove', function (e) {
          move(e)
        })
        window.addEventListener('mousemove', function (e) {
          move(e)
        })

        //鼠标松开
        window.addEventListener('touchend', function () {
          end()
        })
        window.addEventListener('mouseup', function () {
          end()
        })
      }
      onMounted(() => {
        // 禁止拖拽
        init()
        proxy.$el.onselectstart = function () {
          return false
        }
      })
      //鼠标按下
      function start(e) {
        e = e || window.event
        e.preventDefault()
        if (!e.touches) {
          //兼容PC端
          var x = e.clientX
        } else {
          //兼容移动端
          var x = e.touches[0].pageX
        }
        startLeft.value = Math.floor(x - barArea.value.getBoundingClientRect().left)
        startMoveTime.value = +new Date() //开始滑动的时间
        if (isEnd.value == false) {
          // text.value = ''
          moveBlockBackgroundColor.value = '#38f'
          leftBarBorderColor.value = 'rgba(51, 136, 255, 0.16)'
          leftBarBackgroundColor.value = 'rgba(51, 136, 255, 0.16)'
          e.stopPropagation()
          status.value = true
        }
      }
      //鼠标移动
      function move(e) {
        e = e || window.event
        if (status.value && isEnd.value == false) {
          if (!e.touches) {
            //兼容PC端
            var x = e.clientX
          } else {
            //兼容移动端
            var x = e.touches[0].pageX
          }
          const bar_area_left = barArea.value.getBoundingClientRect().left
          let move_block_left = x - bar_area_left //拖动点相对于父元素的left值
          if (move_block_left >= barArea.value.offsetWidth - parseInt(props.barSize.height) + startLeft.value) {
            move_block_left = barArea.value.offsetWidth - parseInt(props.barSize.height) + startLeft.value
          }
          if (move_block_left <= startLeft.value) {
            move_block_left = startLeft.value
          }
          //拖动后小方块的left值
          moveBlockLeft.value = move_block_left - startLeft.value + 'px'
          leftBarWidth.value = move_block_left - startLeft.value + 'px'
        }
      }

      //鼠标松开
      function end() {
        endMoveTime.value = +new Date()
        //判断是否重合
        if (status.value && isEnd.value == false) {
          var moveLeftDistance = parseInt((moveBlockLeft.value || '').replace('px', ''))
          moveLeftDistance = (moveLeftDistance * 310) / parseInt(setSize.imgWidth)
          let data = {
            captchaType,
            pointJson: secretKey.value
              ? aesEncrypt(JSON.stringify({ x: moveLeftDistance, y: 5.0 }), secretKey.value)
              : JSON.stringify({ x: moveLeftDistance, y: 5.0 }),
            token: backToken.value
          }
          $store.dispatch('user/captchaCheck', data).then((res) => {
            if (res.code == '200') {
              moveBlockBackgroundColor.value = '#2da641'
              leftBarBorderColor.value = 'rgba(45, 166, 65, 0.4)'
              leftBarBackgroundColor.value = 'rgba(45, 166, 65, 0.08)'
              iconClass.value = 'icon-066'
              showRefresh.value = false
              isEnd.value = true
              setTimeout(() => {
                proxy.$parent.clickShow = false
                refresh()
              }, 1500)
              passFlag.value = true
              text.value = '验证成功'
              // tipWords.value = `${((endMoveTime.value - startMoveTime.value) / 1000).toFixed(2)}s验证成功`
              var captchaVerification = secretKey.value
                ? aesEncrypt(backToken.value + '---' + JSON.stringify({ x: moveLeftDistance, y: 5.0 }), secretKey.value)
                : backToken.value + '---' + JSON.stringify({ x: moveLeftDistance, y: 5.0 })
              setTimeout(() => {
                // tipWords.value = ''
                proxy.$parent.closeBox()
                proxy.$parent.$emit('success', { captchaVerification })
              }, 1000)
            } else {
              moveBlockBackgroundColor.value = '#df4545'
              leftBarBorderColor.value = 'rgba(223, 69, 69, 0.4)'
              leftBarBackgroundColor.value = 'rgba(223, 69, 69, 0.1)'
              iconClass.value = 'icon-073'
              passFlag.value = false
              setTimeout(function () {
                refresh()
              }, 1000)
              proxy.$parent.$emit('error', proxy)
              text.value = '验证失败'
              // tipWords.value = '验证失败'
              // setTimeout(() => {
              //   tipWords.value = ''
              // }, 1000)
            }
          })
          status.value = false
        }
      }

      const refresh = () => {
        showRefresh.value = true
        finishText.value = ''

        transitionLeft.value = 'left .3s'
        moveBlockLeft.value = 0

        leftBarWidth.value = undefined
        transitionWidth.value = 'width .3s'

        leftBarBorderColor.value = '#ddd'
        leftBarBackgroundColor.value = 'rgba(51, 136, 255, 0.16)'
        moveBlockBackgroundColor.value = '#38f'
        iconClass.value = 'icon-075'
        isEnd.value = false

        getPicture()
        setTimeout(() => {
          transitionWidth.value = ''
          transitionLeft.value = ''
          text.value = props.explain
        }, 300)
      }

      // 请求背景图片和验证图片
      function getPicture() {
        let data = {
          captchaType,
          clientUid: uuidv4()
        }
        $store.dispatch('user/captchaGet', data).then((res) => {
          backImgBase.value = res.data.originalImageBase64
          blockBackImgBase.value = res.data.jigsawImageBase64
          backToken.value = res.data.token
          secretKey.value = res.data.secretKey
        })
      }
      return {
        secretKey, //后端返回的ase加密秘钥
        passFlag, //是否通过的标识
        backImgBase, //验证码背景图片
        blockBackImgBase, //验证滑块的背景图片
        backToken, //后端返回的唯一token值
        startMoveTime, //移动开始的时间
        endMoveTime, //移动结束的时间
        tipsBackColor, //提示词的背景颜色
        tipWords,
        text,
        finishText,
        setSize,
        top,
        left,
        moveBlockLeft,
        leftBarWidth,
        // 移动中样式
        moveBlockBackgroundColor,
        leftBarBorderColor,
        leftBarBackgroundColor,
        iconClass,
        status, //鼠标状态
        isEnd, //是够验证完成
        showRefresh,
        transitionLeft,
        transitionWidth,
        barArea,
        refresh,
        start
      }
    }
  }
</script>
